package com.ruoyi.project.ledger.service.impl;

import java.util.List;
import java.util.Map;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.ledger.domain.LedgerFile;
import com.ruoyi.project.ledger.mapper.LedgerFileMapper;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.ledger.mapper.LedgerBusinessAccountMapper;
import com.ruoyi.project.ledger.domain.LedgerBusinessAccount;
import com.ruoyi.project.ledger.service.ILedgerBusinessAccountService;

/**
 * 经营户台账Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-05-08
 */
@Service
public class LedgerBusinessAccountServiceImpl implements ILedgerBusinessAccountService 
{

    private static final Logger log = LoggerFactory.getLogger(LedgerBusinessAccountServiceImpl.class);

    @Autowired
    private LedgerBusinessAccountMapper ledgerBusinessAccountMapper;
    @Autowired
    private LedgerFileMapper ledgerFileMapper;

    /**
     * 查询经营户台账
     * 
     * @param id 经营户台账ID
     * @return 经营户台账
     */
    @Override
    public LedgerBusinessAccount selectLedgerBusinessAccountById(Long id)
    {
        LedgerBusinessAccount account = ledgerBusinessAccountMapper.selectLedgerBusinessAccountById(id);
        if(account != null){
            // 获取图片
            LedgerFile ledgerFile = new LedgerFile();
            ledgerFile.setLedgerId(id);
            ledgerFile.setLedgerType("2");      // 经营户台账
            List<Map<String, Object>> imgList = ledgerFileMapper.selectLedgerImgList(ledgerFile);
            account.setImgList(imgList);
        }
        return account;
    }

    /**
     * 查询经营户台账列表
     * 
     * @param ledgerBusinessAccount 经营户台账
     * @return 经营户台账
     */
    @Override
    public List<LedgerBusinessAccount> selectLedgerBusinessAccountList(LedgerBusinessAccount ledgerBusinessAccount)
    {
        return ledgerBusinessAccountMapper.selectLedgerBusinessAccountList(ledgerBusinessAccount);
    }

    /**
     * 新增经营户台账
     * 
     * @param ledgerBusinessAccount 经营户台账
     * @return 结果
     */
    @Override
    public int insertLedgerBusinessAccount(LedgerBusinessAccount ledgerBusinessAccount)
    {
        ledgerBusinessAccount.setCreateTime(DateUtils.getNowDate());
        int i = ledgerBusinessAccountMapper.insertLedgerBusinessAccount(ledgerBusinessAccount);
        // 添加图片
        if(ledgerBusinessAccount.getImgs() != null && ledgerBusinessAccount.getImgs().length > 0){
            for(String path : ledgerBusinessAccount.getImgs()){
                LedgerFile ledgerFile = new LedgerFile();
                ledgerFile.setLedgerType("2");    // 经营户台账
                ledgerFile.setLedgerId(ledgerBusinessAccount.getId());
                ledgerFile.setFilePath(path);
                ledgerFile.setCreateId(ledgerBusinessAccount.getCreateId());
                ledgerFile.setCreateTime(DateUtils.getNowDate());
                ledgerFileMapper.insertLedgerFile(ledgerFile);
            }
        }
        return i;
    }

    /**
     * 修改经营户台账
     * 
     * @param ledgerBusinessAccount 经营户台账
     * @return 结果
     */
    @Override
    public int updateLedgerBusinessAccount(LedgerBusinessAccount ledgerBusinessAccount)
    {
        ledgerBusinessAccount.setUpdateTime(DateUtils.getNowDate());
        int i = ledgerBusinessAccountMapper.updateLedgerBusinessAccount(ledgerBusinessAccount);
        // 删除台账图片
        LedgerFile ledgerFile = new LedgerFile();
        ledgerFile.setLedgerId(ledgerBusinessAccount.getId());
        ledgerFile.setLedgerType("2");      // 经营户台账
        ledgerFileMapper.deleteLedgerImg(ledgerFile);
        if(ledgerBusinessAccount.getImgs() != null && ledgerBusinessAccount.getImgs().length > 0){
            for(String path : ledgerBusinessAccount.getImgs()){
                ledgerFile = new LedgerFile();
                ledgerFile.setLedgerType("2");    // 经营户台账
                ledgerFile.setLedgerId(ledgerBusinessAccount.getId());
                ledgerFile.setFilePath(path);
                ledgerFile.setCreateId(ledgerBusinessAccount.getUpdateId());
                ledgerFile.setCreateTime(DateUtils.getNowDate());
                ledgerFileMapper.insertLedgerFile(ledgerFile);
            }
        }
        return i;
    }

    /**
     * 批量删除经营户台账
     * 
     * @param ids 需要删除的经营户台账ID
     * @return 结果
     */
    @Override
    public int deleteLedgerBusinessAccountByIds(Long[] ids)
    {
        int i = ledgerBusinessAccountMapper.deleteLedgerBusinessAccountByIds(ids);
        for(Long id : ids){
            // 删除台账图片
            LedgerFile ledgerFile = new LedgerFile();
            ledgerFile.setLedgerId(id);
            ledgerFile.setLedgerType("2");      // 经营户台账
            ledgerFileMapper.deleteLedgerImg(ledgerFile);
        }
        return i;
    }

    /**
     * 删除经营户台账信息
     * 
     * @param id 经营户台账ID
     * @return 结果
     */
    @Override
    public int deleteLedgerBusinessAccountById(Long id)
    {
        int i = ledgerBusinessAccountMapper.deleteLedgerBusinessAccountById(id);
        // 删除台账图片
        LedgerFile ledgerFile = new LedgerFile();
        ledgerFile.setLedgerId(id);
        ledgerFile.setLedgerType("2");      // 经营户台账
        ledgerFileMapper.deleteLedgerImg(ledgerFile);
        return i;
    }

    @Override
    public String importAccount(List<LedgerBusinessAccount> accountList, Boolean isUpdateSupport, String operName,Long stationId) {
        if (StringUtils.isNull(accountList) || accountList.size() == 0)
        {
            throw new CustomException("导入经营户不能为空！");
        }
        if (stationId == null){
            throw new CustomException("角色异常！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        int i=1;
        for (LedgerBusinessAccount account : accountList){
            i++;
            try{
                if (StringUtils.isBlank(account.getCompanyName())){
                    failureNum++;
                    failureMsg.append("<br/>第" + i + "行、企业名称不能为空");
                    continue;
                }
                if (StringUtils.isBlank(account.getBusinessLicenseNo())){
                    failureNum++;
                    failureMsg.append("<br/>第" + i + "行、营业执照号不能为空");
                    continue;
                }
                account.setStationId(stationId);
                account.setCreateId(String.valueOf(stationId));
                account.setEnteringDate(DateUtils.getNowDate());
                LedgerBusinessAccount a = ledgerBusinessAccountMapper.selectLedgerBusinessAccountByBusinessLicenseNo(account.getBusinessLicenseNo(),stationId);
                if (StringUtils.isNull(a)){
                    account.setCreateBy(operName);
                    account.setCreateTime(DateUtils.getNowDate());
                    this.insertLedgerBusinessAccount(account);
                    successNum++;
                    successMsg.append("<br/>第" + i + "行、企业" + account.getCompanyName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    account.setUpdateBy(operName);
                    this.updateLedgerBusinessAccount(account);
                    successNum++;
                    successMsg.append("<br/>第" + i + "行、企业" + account.getCompanyName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>第" + i + "行、企业" + account.getCompanyName() + " 已存在");
                }

            }catch (Exception e){
                failureNum++;
                String msg = "<br/>第" + i + "行、企业" + account.getCompanyName() + " 导入失败：";
//                failureMsg.append(msg + e.getMessage());
                failureMsg.append(msg + "该行数据信息有误，请仔细检查");
                log.error(msg, e);
            }

        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String checkBusinessLicenseNoUnique(String businessLicenseNo,Long stationId) {
        LedgerBusinessAccount a = ledgerBusinessAccountMapper.selectLedgerBusinessAccountByBusinessLicenseNo(businessLicenseNo,stationId);
        if (a != null){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkBusinessLicenseNoUnique2(LedgerBusinessAccount ledgerBusinessAccount) {
        Long id = StringUtils.isNull(ledgerBusinessAccount.getId()) ? -1L : ledgerBusinessAccount.getId();
        LedgerBusinessAccount a = ledgerBusinessAccountMapper.selectLedgerBusinessAccountByBusinessLicenseNo(ledgerBusinessAccount.getBusinessLicenseNo(),ledgerBusinessAccount.getStationId());
        if (StringUtils.isNotNull(a) && a.getId().longValue() != id.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
